package com.zhanghe.study.thread.aqs;

import java.util.concurrent.Exchanger;

/**
 * @author zh
 * @date 2022/1/5 18:12
 */
public class TestExchanger {

    public static void main(String[] args) {
        // 两个线程交换数据
        Exchanger<String> exchanger = new Exchanger<>();
        ThreadA threadA = new ThreadA(exchanger);
        ThreadB threadB = new ThreadB(exchanger);
        threadA.start();
        threadB.start();
    }

    static class ThreadA extends Thread{
        private Exchanger<String> exchanger;

        public ThreadA(Exchanger<String> exchanger){
            super();
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try{
                System.out.println("线程A中得到的线程B的值为"+exchanger.exchange("【线程A的值】"));
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    static class ThreadB extends Thread{
        private Exchanger<String> exchanger;

        public ThreadB(Exchanger<String> exchanger){
            super();
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try{
                System.out.println("线程B中得到的线程A的值为"+exchanger.exchange("【线程B的值】"));
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
